package com.example.uiwidegt.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.uiwidegt.R;

/**
 * Created by zhudongao
 * Desc
 * Date 2020/10/18
 */

public class GradientTextView extends androidx.appcompat.widget.AppCompatTextView {

    private int startColor;
    private int endColor;
    private Rect textBound = new Rect();
    private Paint paint;
    private LinearGradient linearGradient;
    private int viewWidth;

    public GradientTextView(@NonNull Context context) {
        this(context, null);
    }

    public GradientTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GradientTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientTextView, defStyleAttr, 0);
        startColor = typedArray.getColor(R.styleable.GradientTextView_start_color, Color.parseColor("#000000"));
        endColor = typedArray.getColor(R.styleable.GradientTextView_end_color, Color.parseColor("#000000"));
        typedArray.recycle();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        linearGradient = new LinearGradient(0, 0, viewWidth, 0, new int[]{startColor, endColor}, null, Shader.TileMode.CLAMP);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        viewWidth = getMeasuredWidth();
        paint = getPaint();
        String text = getText().toString();
        paint.getTextBounds(text, 0, text.length(), textBound);
        paint.setShader(linearGradient);
        canvas.drawText(text, getMeasuredWidth() / 2f - textBound.width() / 2f,
                getMeasuredHeight() / 2f + textBound.height() / 2f, paint);
    }
}
